<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="我的积分" left-text="返回" left-arrow @click-left="onClickLeft" />

    <!-- 我的积分 -->
    <div class="my-points">
      <div class="points-text">
        <span>我的积分： </span>
        <span class="points">{{ text }}</span>
      </div>
    </div>

    <!-- 积分变化历史 -->
    <div class="history-section">
      <div class="history-title">积分变化历史</div>

      <!-- 最近的5条历史记录 -->
      <div v-for="(history, index) in recentPointHistory" :key="index" class="history-item">
        <div class="history-date">{{ history.date }}</div>
        <div class="history-amount">{{ history.changeAmount }} 积分</div>
      </div>

      <!-- 查看全部历史按钮 -->
      <van-button v-if="showAllHistoryButton" type="primary" @click="viewAllHistory" class="view-all-btn">
        查看全部历史
      </van-button>

      <!-- 提示文本 -->
      <div class="history-info-text">(每次查看如积分没有变化则重新记录当前积分)</div>

      <!-- 新增积分兑换物品部分 -->
      <div class="items-section">
        <h3>积分兑换物品</h3>
<!--        兑换记录按钮-->
        <van-button type="primary" @click="getOder()" class="redeem-btn">兑换记录</van-button>

      </div>
      <div class="items-section">
        <div class="item" v-for="(item, index) in items" :key="index">
          <img :src="item.img" alt="Item Image" class="item-image">
          <div class="item-description">
            <h3>{{ item.goodsName }}</h3>
            <p>{{ item.pointUse }}积分</p>
            <p>剩余数量{{ item.num }}</p>
            <van-button type="info" @click="redeemPoints(item)" class="redeem-btn">去兑换</van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { GetUserInfo } from '@/api/user.js';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import {goodList, oderOne} from "@/api/goods";
import {ElMessage} from "element-plus"; // 导入 useRouter

const router = useRouter(); // 获取 router 实例

// 点击返回按钮
const onClickLeft = () => {
  router.push('/mine/index'); // 跳转到上一个页面
};

// 用户信息
const text = ref(0); // 当前积分
const name = ref('');
const userId = ref(null); // 用于存储当前登录用户的 ID

// 获取用户信息并存储用户 ID
function getUserInfo1() {
  GetUserInfo()
      .then(res => {
        if (res.data.code === 200000) {
          userId.value = res.data.data.id; // 获取用户 ID 并存储
          console.log("登录用户 ID:", userId.value);
          loadPointHistory(); // 获取用户积分历史
        } else {
          console.error('获取用户信息失败:', res.data.message);
        }
      })
      .catch(err => {
        console.error("获取用户信息出错:", err);
      });
}
getUserInfo1();

// 积分变化历史记录
const pointHistory = ref([]);
const recentPointHistory = ref([]);
const showAllHistoryButton = ref(true);

// 从 localStorage 获取积分历史记录
const loadPointHistory = () => {
  if (!userId.value) {
    console.error("当前用户 ID 尚未获取，无法加载历史记录");
    return;
  }

  const historyKey = `pointHistory-${userId.value}`; // 使用用户 ID 作为 localStorage 键的一部分
  const history = localStorage.getItem(historyKey);
  try {
    if (history) {
      pointHistory.value = JSON.parse(history);
      recentPointHistory.value = pointHistory.value.slice(-5); // 获取最后5条记录
    } else {
      pointHistory.value = [];
      recentPointHistory.value = [];
    }
  } catch (error) {
    console.error("加载历史记录时出错：", error);
    pointHistory.value = [];
    recentPointHistory.value = [];
  }
};

// 更新积分历史记录
const updatePointHistory = (changeAmount) => {
  if (!userId.value) {
    console.error("当前用户 ID 尚未获取，无法更新历史记录");
    return;
  }

  const currentDate = new Date().toLocaleString();
  const newHistory = { date: currentDate, changeAmount };
  const historyKey = `pointHistory-${userId.value}`;

  if (changeAmount !== 0) {
    pointHistory.value.push(newHistory);

    if (pointHistory.value.length > 100) {
      pointHistory.value.shift(); // 删除最早的一条记录
    }

    localStorage.setItem(historyKey, JSON.stringify(pointHistory.value));
    recentPointHistory.value = pointHistory.value.slice(-5);
  }
};

// 获取用户信息并处理积分变化
const getUserInfo = () => {
  GetUserInfo()
      .then(res => {
        if (res.data.code === 200000) {
          const newPoints = res.data.data.point;
          if (newPoints !== text.value) {
            const pointChange = newPoints - text.value;
            text.value = newPoints;
            updatePointHistory(pointChange);
          }
          name.value = res.data.data.userName;
        }
      })
}

// 每隔一定时间检查积分变化
setInterval(getUserInfo, 5000); // 每5秒检查一次积分变化

// 查看全部历史记录
const viewAllHistory = () => {
  showAllHistoryButton.value = false;
  recentPointHistory.value = pointHistory.value;
};

// 页面加载时立即加载历史记录
getUserInfo();

// 积分兑换物品数据
const items = ref({
  img:"",
  goodsName:"",
  pointUse:"",
  num:""
});

//获取兑换商品
function getGoodsList(){
  goodList().then(res => {
    if (res.data.code === 200000) {
      console.log(res.data.data)
      items.value = res.data.data;
    }
  })
}
getGoodsList();

// 兑换积分物品
const redeemPoints = (item) => {
  console.log(item)
  oderOne(item.id).then(res => {
    if (res.data.code === 200000){
      ElMessage.success("兑换成功")
      // router.push('/my/chargeMoneys');
      getGoodsList();
    }else {
      ElMessage.error(res.data.errorMessage);
    }
  })
};
//跳转到兑换记录页面
const getOder = () => {
  router.push('/getOrder');
};
</script>

<style scoped>
/* 自定义页面样式 */

/* 我的积分部分 */
.my-points {
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin: 12px 0;
}

.points-text {
  font-size: 24px;
  text-align: center;
}

.points {
  font-size: 28px;
  color: red;
  font-weight: bold;
}

/* 积分变化历史部分 */
.history-section {
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin-top: 12px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.history-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.history-item {
  margin-bottom: 10px;
  font-size: 16px;
  color: #555;
}

.history-date {
  font-weight: bold;
}

.history-amount {
  color: green;
}

.view-all-btn {
  margin-top: 12px;
}

.history-info-text {
  font-size: 14px;
  color: #888;
  margin-top: 10px;
}

/* 按钮样式 */
.van-button {
  margin-top: 12px;
}

/* 积分兑换物品部分 */
.items-section {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-top: 24px;
}

.item {
  width: 45%;
  margin-bottom: 24px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.item-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-bottom: 16px;
}

.item-description {
  text-align: center;
}

.redeem-btn {
  margin-top: 16px;
}
</style>
